//
//  RegisterOneViewController.m
//  HTP
//
//  Created by 陈钱钿 on 15/11/1.
//  Copyright © 2015年 nit. All rights reserved.
//

#import "RegisterOneViewController.h"
#import "RegisterTwoViewController.h"
#import "UserVM.h"

@interface RegisterOneViewController ()
@property (nonatomic, retain) UITextField *Field;
@property (nonatomic, retain) UIButton *getBtn;
@property (nonatomic, retain) UIButton *selectBtn;
@end

@implementation RegisterOneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //监听文本改动
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:self.Field];
    [self initUI];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    [self addCustomTitleWithTitle:@"验证手机号码"];
    [self addCustomBackBase];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navBG"] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage imageNamed:@"clearBg"]];
    
}
//TODO:绘制UI
- (void)initUI {
    self.Field = [[UITextField alloc] initWithFrame:CGRectMake((ScreenWidth-150)/2, ScreenHeihgt/4, 150, 30)];
    self.Field.placeholder = @"   请输入手机号";
    self.Field.keyboardType = UIKeyboardTypePhonePad;
    self.Field.font = [UIFont systemFontOfSize:18];
    [self.Field setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];
    [self.view addSubview:self.Field];
    
    UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake((ScreenWidth-200)/2, CGRectGetMaxY(self.Field.frame), 200, 2)];
    line.image = [UIImage imageNamed:@"black_line"];
    line.alpha = 0.5;
    [self.view addSubview:line];
    
    self.getBtn = [[UIButton alloc] initWithFrame:CGRectMake((ScreenWidth-200)/2, CGRectGetMaxY(line.frame)+50, 200, 40)];
    [self.getBtn setBackgroundImage:[UIImage imageNamed:@"get_gray"] forState:UIControlStateNormal];
    self.getBtn.enabled = NO;
    [self.getBtn addTarget:self action:@selector(getMessageClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.getBtn];
    
    self.selectBtn = [[UIButton alloc] initWithFrame:CGRectMake((ScreenWidth-200)/2, CGRectGetMaxY(self.getBtn.frame)+10, 15, 15)];
    //未选择是1 选中是2
    self.selectBtn.tag = 1;
    [self.selectBtn setBackgroundImage:[UIImage imageNamed:@"primary"] forState:UIControlStateNormal];
    [self.selectBtn addTarget:self action:@selector(selectBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.selectBtn];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.selectBtn.frame)+5, CGRectGetMaxY(self.getBtn.frame)+10, 230, 15)];
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"我已阅读并同意青苗家教《用户协议》"];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(0, 7)];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:NSMakeRange(7, 10)];
    label.attributedText = str;
    label.font = [UIFont systemFontOfSize:13];
    [self.view addSubview:label];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

/*
 监听 文本框内改变
 */
- (void)textChange {
    if(self.Field.text.length == 11 && self.selectBtn.tag == 2){
        [self.getBtn setBackgroundImage:[UIImage imageNamed:@"get_light"] forState:UIControlStateNormal];
        self.getBtn.enabled = YES;
    } else{
        [self.getBtn setBackgroundImage:[UIImage imageNamed:@"get_gray"] forState:UIControlStateNormal];
        self.getBtn.enabled = NO;
    }
}

/*
 阅读协议框的点击
 */
- (void)selectBtnClick {
    if(self.selectBtn.tag == 1){ //未选中改为选中
        [self.selectBtn setBackgroundImage:[UIImage imageNamed:@"tick"] forState:UIControlStateNormal];
        if(self.Field.text.length == 11){
            [self.getBtn setBackgroundImage:[UIImage imageNamed:@"get_light"] forState:UIControlStateNormal];
            self.getBtn.enabled = YES;
        }else {
            [self.getBtn setBackgroundImage:[UIImage imageNamed:@"get_gray"] forState:UIControlStateNormal];
            self.getBtn.enabled = NO;
        }
        self.selectBtn.tag = 2;
    } else { //选中改为未选中
        [self.selectBtn setBackgroundImage:[UIImage imageNamed:@"primary"] forState:UIControlStateNormal];
        self.selectBtn.tag = 1;
        [self.getBtn setBackgroundImage:[UIImage imageNamed:@"get_gray"] forState:UIControlStateNormal];
        self.getBtn.enabled = NO;
    }
}

/*
 获取短信验证码的点击
 */
- (void)getMessageClick {
    if (![self validateMobile:_Field.text]) {
        [self showSVProgressFailed:@"手机格式错误"];
        return;
    }
    [self sendSms];
}
-(void)sendSms{
    NSString *rands = [self randS];
    UserVM *userVM = [[UserVM alloc] init];
    [userVM setBlockWithReturnBlock:^(id returnValue) {
        RegisterTwoViewController *twoVc = [[RegisterTwoViewController alloc] init];
        twoVc.randS = rands;
        twoVc.userName = self.Field.text;
        [self.navigationController pushViewController:twoVc animated:YES];
    } WithErrorBlock:^(id errorCode) {
        [self showSVProgressFailed:@"获取验证码失败"];
    } WithFailureBlock:^{
        [self showSVProgressFailed:@"获取验证码失败"];
    }];
    [userVM sendRands:self.Field.text andSMSRand:rands];
}
-(NSString *) randS{
    NSString *strRandom = @"";
    
    for(int i=0; i < 6; i++)
    {
        strRandom = [ strRandom stringByAppendingFormat:@"%i",(arc4random() % 10)];
    }
    NSLog(@"验证码是----------%@",strRandom);
    
    return strRandom;
}
- (BOOL)validateMobile:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    //    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[0235-9])\\d{8}$";
    NSString * MOBILE_1 = @"^1\\d{10}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE_1];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
